package yki.paperplane.server.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;

import yki.paperplane.server.db.DBConstant;
import yki.paperplane.server.db.useroperator.CheckPasswordValidOperator;
import yki.paperplane.server.utils.XMLUtils;

public abstract class BaseServlet extends HttpServlet{
	
	private static DataSource mDataSource;
	
	public static final String STATUSCODE = "StatusCode";
	
	protected static final String DATEFORMATSTRING = "yyyy-mm-dd";
	protected static SimpleDateFormat mDate_Format= new SimpleDateFormat(DATEFORMATSTRING);
		
	protected static Connection getDBConnection() throws SQLException, NamingException {
		if( mDataSource==null ){
			InitialContext context = new InitialContext();
			mDataSource = (DataSource)context.lookup( DBConstant.DB_ADDRESS );
		}
		return mDataSource.getConnection();
	}
	
	
	protected int getUserID( Connection connection, String email, String password ) throws SQLException{
		CheckPasswordValidOperator operator = new CheckPasswordValidOperator(email, password);
//		int id = operator.execute(connection);
//		if( id == -1 )
//			throw new PasswordErrorException();
		return operator.execute(connection);
	}
	
	protected int getUserID( Connection connection, int user_id, String password) throws SQLException{
		CheckPasswordValidOperator operator = new CheckPasswordValidOperator(user_id, password);
		return operator.execute(connection);
	}

	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.service( request, response);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	}

	protected static void handleWrongPasswordException( HttpServletResponse response) {
		response.addHeader( STATUSCODE, StatusCode.STATUS_INCORRECT_PASSWORD+"");
	}

}
